<?php
namespace App\Models\Traits;
use App\Models\Coupon;
use App\Models\User;
use App\Models\CouponsConfig;
use Illuminate\Support\Carbon;
use App\Notifications\CouponsSend;
trait CouponAddSelfHelper{
    public static  function addCoupon(int $user_id,int $coupons_config_id){
        //没发放过这个券的
        if (Coupon::where(['user_id'=>$user_id,'coupons_config_id'=>$coupons_config_id])->count()<=0)
        {
            $coupon = new self();
//        dd($coupon);
            $user = User::find($user_id);
            $couponsConfig = CouponsConfig::find($coupons_config_id);
            $coupon->user()->associate($user);
            $coupon->couponsConfig()->associate($couponsConfig);
            $coupon->title = $couponsConfig->title;
            $coupon->descript = $couponsConfig->descript;
            $coupon->type = $couponsConfig->type;
            $coupon->end_date = Carbon::now()
                ->addDays($couponsConfig->expire_day)
                ->toDateString();
            $coupon->save();
            //只要发送完礼品券就添加消息通知
            $user->couponNotify(new CouponsSend($coupon));
        }

    }
}
